package org.raymond.iworks.study.basic.thread.concurrenthashmap;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Phaser;

@Slf4j
public class Demo1 {
    private static ConcurrentHashMap<String, Object> cache = new ConcurrentHashMap();
    public static void main(String[] args) {
        test1();
    }

    public static void test1(){
        Phaser phaser = new Phaser(){
            @Override
            protected boolean onAdvance(int phase, int registeredParties) {
                log.info("{}-{}", "123", cache.get("123"));
                return super.onAdvance(phase, registeredParties);
            }
        };

        Thread t1 = new Thread(()->{
            cache.putIfAbsent("123", 1);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            phaser.arriveAndDeregister();
            log.info("1");
        });
        Thread t2 = new Thread(()->{
            cache.putIfAbsent("123", 2);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            phaser.arriveAndDeregister();
            log.info("2");
        });
        Thread t3 = new Thread(()->{
            cache.putIfAbsent("123", 3);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            phaser.arriveAndDeregister();
            log.info("3");
        });
        phaser.register();
        t1.start();
        phaser.register();
        t2.start();
        phaser.register();
        t3.start();
    }

    static class MyTask implements Runnable {


        @Override
        public void run() {

        }
    }
}


